package cwb1;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.EntityNotFoundException;

public class TrackingFinished extends HttpServlet {
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		
		try {
			Date stopDate = Calendar.getInstance().getTime();
			
			
			
			String userId = req.getParameter("userId");
			String activityId = UserRegistry.getInstance().get(userId).getCurrentActivityId();
			String pauseDurationString = req.getParameter("pauseDuration");
			long pauseDuration = 0;

			if(!pauseDurationString.isEmpty()) {
				pauseDuration = Long.decode(pauseDurationString) * 100;
			}
			
			System.out.println(pauseDuration);
			
			Activity activity = ActivityRegistry.getInstance().get(activityId, userId);
			
			activity.setStopDate(stopDate);
			activity.setPauseDuration(pauseDuration);
			ActivityRegistry.getInstance().update(activity);
			
			User user = UserRegistry.getInstance().get(userId);
			user.setCurrentActivityId(null);
			
			UserRegistry.getInstance().update(user);
			
			
			resp.sendRedirect("main.jsp");
			
			
		}
		catch(EntityNotFoundException e) {
			System.out.println("catch");
		}
		
	}

}
